package com.example.library.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "swtao";  // 秘钥

    // 生成 Token：接收业务数据，将 userEmail、userName、userRole 等单独放在 claim 中
    public static String genToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("userEmail", (String) claims.get("userEmail"))
                .withClaim("userName", (String) claims.get("userName"))
                .withClaim("userRole", (String) claims.get("userRole")) // 添加 userRole
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))  // 12小时有效期
                .sign(Algorithm.HMAC256(KEY));
    }

    // 解析 Token 并返回所有业务数据
    public static Map<String, Claim> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(KEY))
                .build()
                .verify(token)
                .getClaims();
    }


}
